package com.authority.framework.web.controller;

import com.authority.framework.base.entity.DTreeEntity;
import com.authority.framework.base.entity.DTreeIsCheckedEntity;
import com.authority.framework.log.Log;
import com.authority.framework.log.enums.BusinessType;
import com.authority.framework.web.domain.*;
import com.authority.framework.web.service.SysDeptService;
import com.authority.framework.base.util.*;
import com.authority.framework.base.util.laydata.LayDatas;
import com.authority.framework.base.util.laydata.ResultModel;
import com.authority.framework.base.util.laydata.ResultTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: authority
 * @description: 部门控制层
 * @author: Mr.Yan
 * @create: 2018-11-20 18:01
 **/
@Controller
@RequestMapping(value = "sysdeptCon")
public class SysDeptController {
	private static final Logger log = LoggerFactory.getLogger(SysDeptController.class);
	@Autowired
	private SysDeptService sysDeptService;

	private Map<String, Object> paramMap;//参数

	private Map<String, Object> resultMap;//返回值

	/**
	 * 获取用户部门dtree数据
	 *
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/userdtreedate")
	@ResponseBody
	public ResultDTree userdtreedate(HttpServletResponse response, HttpServletRequest request,
			@RequestParam(name = "deptId", required = false) String deptId) {
		List<DTreeEntity> dTrees = sysDeptService.findDTreeData();
		// deptId 一个部门没有复选框
		if (StringUtils.isNotNull(deptId)) {
			for (DTreeEntity dTree : dTrees) {
				//  验证是否选中某个值
				if (deptId.equals(String.valueOf(dTree.getId()))) {
					dTree.setChecked(true);
				}
			}
		}
		dTrees = DTreeUtils.getChildPerms(dTrees, 0);
		ResultDTree r = new ResultDTree();
		r.setData(dTrees);
		Map<String, Object> map = new HashMap<>();
		map.put("code", 200);
		map.put("message", "成功");
		r.setStatus(map);
		return r;
	}

	/**
	 * 获取部门dtree数据
	 *
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/roledtreedate")
	@ResponseBody
	public ResultDTree roledtreedate(HttpServletResponse response, HttpServletRequest request,
			@RequestParam(name = "deptIds", required = false) String deptIds) {
		// 设置选中状态
		List<DTreeIsCheckedEntity> checkArr = DTreeUtils.hasCheckArr();
		List<DTreeEntity> dTrees = sysDeptService.findDTreeData();
		// deptId 一个部门没有复选框
		if (StringUtils.isNotNull(deptIds)) {
			String[] deptIdsSplit = deptIds.split(",");
			for (String deptId : deptIdsSplit) {
				for (DTreeEntity dTree : dTrees) {
					//  验证是否选中某个值
					if (deptId.equals(String.valueOf(dTree.getId()))) {
						dTree.setCheckArr(checkArr);
					}
				}
			}
		}
		dTrees = DTreeUtils.getChildPerms(dTrees, 0);
		ResultDTree r = new ResultDTree();
		r.setData(dTrees);
		Map<String, Object> map = new HashMap<>();
		map.put("code", 200);
		map.put("message", "成功");
		r.setStatus(map);
		return r;
	}

	/**
	 * @Description: 获取部门数据级展示数据
	 * @Param:
	 * @return:
	 * @Author: Mr.Yan
	 * @Date: 2018/12/15
	 */

	@RequestMapping("/list")
	@ResponseBody
	public LayDatas list(HttpServletRequest request, HttpServletResponse response,
			@RequestParam Map<String, Object> ajaxMap) {
		List<SysDeptEntity> deptEntities = sysDeptService.findMenuList(ajaxMap);
		return LayDatas.data(deptEntities);
	}

	/**
	 * @Description: 部门添加
	 * @Param:
	 * @return:
	 * @Author: Mr.Yan
	 * @Date: 2018/12/24
	 */

	@Log(title = "部门管理", businessType = BusinessType.INSERT)
	@RequestMapping("/insert")
	@ResponseBody
	public ResultModel insert(HttpServletRequest request, HttpServletResponse response,
			@RequestParam Map<String, Object> ajaxMap) {
		try {
			//  获取登陆用户信息
			SysUserEntity userEntity = ShiroUtils.getSubjectUser();
			ajaxMap.put("createBy", userEntity.getUserName());
			//  获取当前时间
			String time = DateUtils.getTime();
			ajaxMap.put("createTime", time);
			// 祖籍列表
			String ancestors = "0";
			// 根据父级id查询祖籍列表
			Integer parentId = Integer.valueOf((String)ajaxMap.get("parentId"));
			// 判断是否是主目录 是 祖籍为0 否则查询祖籍加上父级Id为最终祖籍
			if(parentId != 0){
				SysDeptEntity byPrimaryKey = sysDeptService.findByPrimaryKey(SysDeptEntity.class, parentId);
				ancestors = byPrimaryKey.getAncestors() + "," + parentId;
			}
			ajaxMap.put("ancestors",ancestors);
			Integer insert = sysDeptService.insert(SysDeptEntity.class, ajaxMap);
			if (insert > 0) {
				return ResultTools.result(0, "", null);
			} else {
				return ResultTools.result(404, "添加部门信息失败", null);
			}
		}
		catch (Exception e) {
			log.error("添加部门信息出现错误" + e.getMessage());
			return ResultTools.result(404, "添加部门信息出现错误", null);
		}
	}

	/**
	 * @Description: 打开修改部门之前查询列表回显
	 * @Param:
	 * @return:
	 * @Author: Mr.Yan
	 * @Date: 2018/12/24
	 */
	@ResponseBody
	@RequestMapping(value = "/openDeptUpdate")
	public ModelAndView openDeptUpdate(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(name = "deptId", required = false) Integer deptId) {
		ModelAndView mv = new ModelAndView();
		try {
			SysDeptEntity deptEntity = null;
			String parentName = null;
			deptEntity = sysDeptService.findByPrimaryKey(SysDeptEntity.class, deptId);
			parentName = "主目录";
			if (deptEntity.getParentId() != 0) {
				SysDeptEntity parentDeptEntity = sysDeptService.findByPrimaryKey(SysDeptEntity.class, deptEntity.getParentId().intValue());
				parentName = parentDeptEntity.getDeptName();
			}
			mv.addObject("dept", deptEntity);
			mv.addObject("parentName", parentName);
		}
		catch (Exception e) {
			log.error("打开部门修改框出现错误" + e.getMessage());
			e.printStackTrace();
		}

		mv.setViewName("web/system/dept/dept_update");
		return mv;
	}
	/**
	 * @Description: 更新部门信息
	 * @Param:
	 * @return:
	 * @Author: Mr.Yan
	 * @Date: 2018/12/7
	 */
	@Log(title = "部门管理", businessType = BusinessType.UPDATE)
	@ResponseBody
	@RequestMapping(value = "/update")
	public ResultModel update(HttpServletRequest request, HttpServletResponse response,
			@RequestParam Map<String, Object> ajaxMap) {
		try {
			//  获取当前时间
			String time = DateUtils.getTime();
			//  获取登陆用户信息
			SysUserEntity userEntity = ShiroUtils.getSubjectUser();
			ajaxMap.put("updateTime", time);
			ajaxMap.put("updateBy", userEntity.getUserName());
			// 祖籍列表
			String ancestors = "0";
			// 根据父级id查询祖籍列表
			Integer parentId = Integer.valueOf((String)ajaxMap.get("parentId"));
			// 判断是否是主目录 是 祖籍为0 否则查询祖籍加上父级Id为最终祖籍
			if(parentId != 0 ){
				SysDeptEntity byPrimaryKey = sysDeptService.findByPrimaryKey(SysDeptEntity.class, parentId);
				ancestors = byPrimaryKey.getAncestors() + "," + parentId;
			}
			ajaxMap.put("ancestors",ancestors);
			Integer update = sysDeptService.update(SysDeptEntity.class, ajaxMap);
			if (update > 0) {
				return ResultTools.result(0, "", null);
			} else {
				return ResultTools.result(404, "更新部门信息失败", null);
			}
		}
		catch (Exception e) {
			log.error("更新部门信息出现错误" + e.getMessage());
			return ResultTools.result(404, "更新部门信息出现错误", null);
		}
	}

	/**
	 * 删除 部门信息
	 *
	 * @param request
	 * @param response
	 * @param deptIds
	 * @return
	 */
	@Log(title = "部门管理", businessType = BusinessType.DELETE)
	@ResponseBody
	@RequestMapping(value = "/deleteDept")
	public ResultModel deleteDept(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(name = "deptIds", required = false) String deptIds) {
		try {
			String[] deptIdArr = deptIds.split(",");
			for (String deptId : deptIdArr) {
				paramMap = new HashMap<>();
				paramMap.put("parentId", deptId);
				paramMap.put("delFlag", 0);
				Long listByWhereCount = sysDeptService.findListByWhereCount(SysDeptEntity.class, paramMap);
				if (listByWhereCount > 0) {
					SysDeptEntity deptEntity = sysDeptService.findByPrimaryKey(SysDeptEntity.class, Integer.valueOf(deptId));
					return ResultTools.result(404, deptEntity.getDeptName() + "存在子级部门无法删除", null);
				} else {
					paramMap.remove("parentId");
					paramMap.put("deptId", deptId);
					paramMap.replace("delFlag", 2);
					//  获取当前时间
					String time = DateUtils.getTime();
					//  获取登陆用户信息
					SysUserEntity userEntity = ShiroUtils.getSubjectUser();
					paramMap.put("updateTime", time);
					paramMap.put("updateBy", userEntity.getUserName());
					Integer update = sysDeptService.update(SysDeptEntity.class, paramMap);
					if (update < 1) {
						return ResultTools.result(404, "删除部门信息失败", null);
					}
				}
			}
			return ResultTools.result(0, "", null);
		}
		catch (Exception e) {
			log.error("删除部门信息出现未知错误" + e.getMessage());
			return ResultTools.result(404, "删除部门信息出现未知错误", null);
		}
	}

	/**
	 * 验证是否可以移动父级部门信息
	 *
	 * @param request
	 * @param response
	 * @param deptId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/moveParentDeptVerify")
	public ResultModel moveParentDeptVerify(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(name = "deptId", required = false) String deptId) {
		paramMap = new HashMap<>();
		paramMap.put("parentId", deptId);
		paramMap.put("delFlag", 0);
		Long listByWhereCount = sysDeptService.findListByWhereCount(SysDeptEntity.class, paramMap);
		if (listByWhereCount > 0) {
			SysDeptEntity deptEntity = sysDeptService.findByPrimaryKey(SysDeptEntity.class, Integer.valueOf(deptId));
			return ResultTools.result(404, deptEntity.getDeptName() + "存在子级部门无法修改父级部门", null);
		}
		return ResultTools.result(0, "", null);
	}

}
